package com.bridgeintelligent.tag.user.mgmt.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * HttpClient工具类
 */
@Slf4j
public class HttpClientUtil {

    private static final String PROXY_HOST = "XXX.XXX.XXX.XXX";

    private static final String PROXY_PORT = "0000";

    /**
     * @param url
     * @param json
     * @return
     * @Title: doPostJson
     * @author xiangjialiang
     * @date 2021-07-06
     */
    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error("执行httppost请求出现异常",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
            } catch (IOException e) {
                log.error("释放httppost资源出现异常",e);
            }
        }
        return resultString;
    }

    /**
     * @param url
     * @param json
     * @return
     * @Title: doPostJson
     * @author xiangjialiang
     * @date 2018年10月31日 下午4:13:45
     */
    public static String doPostJsonProxy(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            HttpHost proxy = new HttpHost(PROXY_HOST, Integer.valueOf(PROXY_PORT), "http");
            RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
            httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.info("执行doPostJsonProxy请求出现异常",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
            } catch (IOException e) {
                log.info("释放doPostJsonProxy资源出现异常",e);
            }
        }
        return resultString;
    }


    /**
     * @param url
     * @param param
     * @Description: get请求
     * @author xiangjialiang
     * @date 2021-07-06
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象  
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri  
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求  
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求  
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200  
            int i = 200;
            if (response.getStatusLine().getStatusCode() == i) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            log.error("执行doGet请求出现异常",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient != null) {
                    httpclient.close();
                    httpclient = null;
                }
            } catch (IOException e) {
                log.error("释放doGet资源出现异常",e);
            }
        }
        return resultString;
    }

    /**
     * @param url
     * @param param
     * @return
     * @Title: doPost
     * @author xiangjialiang
     * @date 2021-07-06
     */
    public static String doPost(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error("执行doPost请求出现异常",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
            } catch (IOException e) {
                log.error("释放doPost资源出现异常",e);
            }
        }
        return resultString;
    }


    /**
     * 通过代理请求接口
     *
     * @param url
     * @param param
     * @return
     */
    public static String doPostProxy(String url, Map<String, String> param) {
        // 创建Httpclient对象  
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求  
            HttpPost httpPost = new HttpPost(url);
            HttpHost proxy = new HttpHost(PROXY_HOST, Integer.valueOf(PROXY_PORT), "http");
            RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
            httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
            // 创建参数列表  
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求  
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error("执行doPostProxy请求出现异常",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                    response = null;
                }
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
            } catch (IOException e) {
                log.error("释放doPostProxy资源出现异常",e);
            }
        }
        return resultString;
    }

    public static String httpsPost(String url, Map<String, String> param) {
        // 创建Httpclient对象  
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求  
            HttpPost httpPost = new HttpPost(url);
            HttpHost proxy = new HttpHost(PROXY_HOST, Integer.valueOf(PROXY_PORT), "http");
            RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate[] xcs, String string) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).build();

            // 创建参数列表  
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单  
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                httpPost.setEntity(entity);
            }
            // 执行http请求  
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error("执行httpsPost请求出现异常",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                    response = null;
                }
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
            } catch (IOException e) {
                log.error("释放httpsPost资源出现异常",e);
            }
        }
        return resultString;
    }

    public static String httpsPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            HttpHost proxy = new HttpHost(PROXY_HOST, Integer.valueOf(PROXY_PORT), "http");
            RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();

            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                //信任所有
                @Override
                public boolean isTrusted(X509Certificate[] xcs, String string) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(defaultRequestConfig).build();

            // 创建参数列表
            if (json != null) {
                httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
                StringEntity entity = new StringEntity(json);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.info("执行httpsPostJson出现异常",e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                    response = null;
                }
                if (httpClient != null) {
                    httpClient.close();
                    httpClient = null;
                }
            } catch (IOException e) {
                log.info("关闭httpsPostJson资源出现异常",e);
            }
        }
        return resultString;
    }


}


